import { defineStore } from "pinia";
//引入完整的动态路由表
import routes from "@/router/generatorRoutes";
//引入发起请求获取菜单的方法
import * as api from "@/api/permission";
//引入递归求routes的方法
import recursionRoutes from "@/utils/recursionRoutes";
//引入动态路由
import dynamicRoutes from "@/router/dynamicRoutes";
//引入静态路由
import staticRoute from "@/router/staticRoute";
//引入路由对象
import router from "@/router";

export const usePermission = defineStore("permission", {
  state() {
    return {
      menulist: [],
      logout: false, //是否退出
      collapse: false, //菜单是否收起
    };
  },
  actions: {
    fetch_menulist() {
      //发起请求，获取菜单
      return api.getMenuApi().then((res) => {
        // console.log(res);
        // console.log(routes);
        //获取用户路由
        let userRoutes = recursionRoutes(res.data.menuList, routes);
        // console.log(userRoutes);
        this.menulist = userRoutes;
        //开始动态添加路由
        //1.先从动态路由中，找到路径是"/"的路由对象
        let target = dynamicRoutes.find((route) => route.path === "/");
        //2.将用户路由变成它的孩子
        target.children = userRoutes;
        //3.静态路由也要添加到dynamicRoutes的孩子里
        target.children = [...target.children, ...staticRoute];
        //4.使用addRoute方法，将dynamicRoutes添加到路由routes配置中
        // console.log(dynamicRoutes);
        // console.log(target);
        router.addRoute(target);
      });
    },
  },
});
